﻿Imports FL_8x0.FL_800.Model
Imports GalaSoft.MvvmLight
Imports GalaSoft.MvvmLight.CommandWpf
Imports GalaSoft.MvvmLight.Messaging
Imports FL_8x0.Common.SystemData
Imports FL_8x0.Common
Imports System.Collections.ObjectModel
Imports System.Text
Imports FL_8x0.Viewmodel

Namespace FL_8x0.FL_800.ViewModel
    Public Class ProductViewModel
        Inherits ViewModelBase

        Private _msVisiable As Visibility

        Private _notMsVisiable As Visibility

        Private _version113Visable As GridLength
        Private _exhdEnable As Boolean


        Private _groupModel As GroupModel
        Private _applyCmd As RelayCommand
        Private _cancelCmd As RelayCommand

        Private _idList As ObservableCollection(Of String)               '产品Id列表

        Private _addCommand As RelayCommand                              '点击“新增”触发命令
        Private _editCommand As RelayCommand                             '点击“新增”触发命令
        Private _isAdd As Boolean                                        '当前模式 

        Private _strReason As String

        Private _leakUnit As String
        Private _pressureUnit As String

        Private _id As String

        Private _productService As New GroupModel

        Private _groupId As UShort                                            '当前ID

        Private _groupIdList As ObservableCollection(Of String)

        Private _switchGroupCmd As RelayCommand

        Private _isSwitchGroup As Boolean

        Private _locator As ViewModelLocator

        Private _isNot113 As Visibility


        Public Sub New()
            Version113Visable = New GridLength(1, GridUnitType.Star)
            ExhdEnable = True
            IsNot113 = Visibility.Visible
            _productService.IsMs = True
            Messenger.Default.Register(Of Message)(Me, "Group", AddressOf FalshGroup)
            _applyCmd = New RelayCommand(AddressOf Apply)
            _cancelCmd = New RelayCommand(AddressOf Cancel)
            _addCommand = New RelayCommand(AddressOf ReadGroup)
            _editCommand = New RelayCommand(AddressOf Edit)
            If SystemData.Machine = Model_800 Then
                NotMsVisiable = Visibility.Visible
                MsVisiable = Visibility.Collapsed
                _productService.IsMs = False
                If SystemData.Version = Version_800_113 Then
                    Version113Visable = New GridLength(0)
                    ExhdEnable = True
                    IsNot113 = Visibility.Collapsed
                End If
            Else
                NotMsVisiable = Visibility.Collapsed
                MsVisiable = Visibility.Visible
            End If
            IdList = New ObservableCollection(Of String)(User_ListProduct())
            If g_udtReport.ReportId <> "" Then
                If g_udt800.Temporary Then
                    IdList.Add(g_udt800.Id)
                End If
                GroupId = g_udt800.GroupId
                Id = g_udt800.Id
            Else
                _leakUnit = "Pa"
                _pressureUnit = "kPa"
                IsAdd = True
                IdList.Clear()
                ReadGroup()
            End If

            _locator = CType(Application.Current.Resources.Item("Locator"), ViewModelLocator)
            _locator.LeakTest800.IsReadOther = True

            SwitchGroupCmd = New RelayCommand(AddressOf SwitchGroup)

            GroupIdList = New ObservableCollection(Of String)
            For index = 0 To 31
                GroupIdList.Add(Format(index, "00"))
            Next
        End Sub

        Private Sub SwitchGroup()
            _isSwitchGroup = True
            Dim res = SystemData.g_udtFL800Sync.WriteGroupIdSync(GroupId)

            If res Then
                ReadGroup()
            Else
                log.WriteLogWarn("组号切换", "组号切换失败，请检查连接")
            End If
        End Sub

        Private Sub Cancel()
            If IsAdd Then
                IsAdd = True
                IdList.Clear()
                ReadGroup()
            Else
                FillEditModel(GroupModel.Id)
            End If

        End Sub

        Private Sub ReadGroup()
            GroupModel = New GroupModel
            Dim lngId = SystemData.idWorker.nextId()
            GroupModel.Id = lngId
            IdList.Add(lngId)
            Id = lngId

            ' 使用异步方式
            'If SystemData.udtFl800.IsRunning Then
            '    If SystemData.Machine = Model_800 And SystemData.Version <> Version_800_113 Then
            '        SystemData.udtFl800.Write(Chr(SerialPortServer.ENQ) & "8" & Chr(SerialPortServer.ACK), SystemData.ReadGroupCmd)
            '    Else
            '        SystemData.udtFl800.Write(Chr(SerialPortServer.ENQ) & "1" & Chr(SerialPortServer.ACK), SystemData.ReadGroupCmd)
            '    End If
            'End If

            If SystemData.g_udtFL800Sync.IsRunning Then
                If SystemData.Machine = Model_800 And SystemData.Version <> Version_800_113 Then
                    SystemData.g_udtFL800Sync.ReadGroupSync(Chr(SerialPortServer.ENQ) & "8" & Chr(SerialPortServer.ACK))
                Else
                    SystemData.g_udtFL800Sync.ReadGroupSync(Chr(SerialPortServer.ENQ) & "1" & Chr(SerialPortServer.ACK))
                End If
            End If

            'LeakUnit = Trim(GroupModel.LeakUnit)
            'PressureUnit = Trim(GroupModel.PressureUnit)
        End Sub

        Private Sub Apply()
            If g_udtOtherSet.blnAuditMode And String.IsNullOrEmpty(StrReason) Then
                log.WriteLogError("输入参数检查", "您当前处于审计模式，请填写修改原因！")
                Exit Sub
            End If

            GroupModel.Temporary = False
            GroupModel.IsMs = _productService.IsMs
            If GroupModel.Check() Then
                GroupModel.Name = IIf(GroupModel.Name = "", "未命名", GroupModel.Name)
                GroupModel.Model = IIf(GroupModel.Model = "", "空", GroupModel.Model)
                Dim sb5, sb6, sb7, sb8 As New StringBuilder
                For i = 7 To 0 Step -1
                    sb5.Append(IIf(GroupModel.Sv5List(i), "1", "0"))
                    sb6.Append(IIf(GroupModel.Sv6List(i), "1", "0"))
                    sb7.Append(IIf(GroupModel.Sv7List(i), "1", "0"))
                    sb8.Append(IIf(GroupModel.Sv8List(i), "1", "0"))
                Next
                GroupModel.SV5Mode = sb5.ToString
                GroupModel.Sv6Mode = sb6.ToString
                GroupModel.SV7Mode = sb7.ToString
                GroupModel.SV8Mode = sb8.ToString

                GroupModel.GroupId = GroupId
                Dim blnShouldWrite As Boolean = GroupModel.Id = g_udt800.Id AndAlso g_udtFL800Sync.IsRunning
                Dim result As Boolean = GroupModel.WriteProduct(Database.g_dbConn测试记录, StrReason, blnShouldWrite)

                Dim udt800Pre As GroupModel = g_udt800

                If g_udtFL800Sync.IsRunning AndAlso Not blnShouldWrite Then
                    g_udt800 = GroupModel
                    result = WriteProduct()
                    If Not result Then
                        'g_udtReport.ReportId = ""
                        g_udt800 = udt800Pre
                        MessageBox.Show("数据写入失败")
                        Exit Sub
                    End If
                End If

                If result Then
                    StrReason = ""
                    MsgBox("保存成功", MsgBoxStyle.OkOnly, "提示")
                    Messenger.Default.Send("OK", "update_product")
                Else
                    g_udt800 = udt800Pre
                End If
            End If
        End Sub

        Private Sub FalshGroup(m As Message)
            Dim group = TryCast(m.Msg, GroupModel)
            If group IsNot Nothing Then

                If _isSwitchGroup Then
                    group.Name = group.GroupId & "自动添加" & Date.Now.ToString("yyyy年MM月dd日 HH时mm分ss秒")
                End If
                GroupModel = group
                GroupModel.Id = Id
                GroupId = group.GroupId
                If SystemData.Version = Version_800_113 Then
                    GroupModel.Times(8) = 0.0
                    GroupModel.MiddleJudgment = False
                    GroupModel.TestPDAC = 0
                    GroupModel.LeadPDAC = 0
                End If
                LeakUnit = Trim(GroupModel.LeakUnit)
                PressureUnit = Trim(GroupModel.PressureUnit)

                If _isSwitchGroup Then
                    GroupModel.Temporary = True
                    GroupModel.WriteProduct(g_dbConn测试记录, "切换组号新增", False)
                    g_udt800 = GroupModel
                    Messenger.Default.Send(Of String)("OK", "update_product")
                    _isSwitchGroup = False
                End If
            End If
        End Sub


        Private Function WriteProduct() As Boolean
            If g_udt800.IsMs Then
                Return g_udtFL800Sync.WriteGroupSync(Chr(SerialPortServer.ENQ) & "2")
            Else
                If Version = Version_800_113 Then
                    Return g_udtFL800Sync.WriteGroupSync(Chr(SerialPortServer.ENQ) & "2")
                Else
                    Return g_udtFL800Sync.WriteGroupSync(Chr(SerialPortServer.ENQ) & "9")
                End If
            End If
        End Function

        '=====================================================================
        '函 数 名: Edit
        '参    数: 
        '返 回 值:
        '功能描述: 点击编辑按钮
        '=====================================================================
        Private Sub Edit()
            IdList.Clear()
            Dim ids = User_ListProduct()

            If ids.Count > 0 Then
                For Each strId As String In ids
                    IdList.Add(strId)
                Next
                Id = ids(0)
            Else
                MsgBox("当前没有产品，请先添加", MsgBoxStyle.OkOnly, "错误")
                ReadGroup()
            End If
        End Sub

        '=====================================================================
        '函 数 名: FillEditModel
        '参    数: strId 产品Id号
        '返 回 值:
        '功能描述: 读取数据库数据填充ProductModel
        '=====================================================================
        Private Sub FillEditModel(ByVal strId As String)
            IsAdd = False
            GroupModel = _productService.ReadProduct(Database.g_dbConn测试记录, strId)
            'GroupId = GroupModel.GroupId
            LeakUnit = Trim(GroupModel.LeakUnit)
            PressureUnit = Trim(GroupModel.PressureUnit)
        End Sub

        Public Property MsVisiable As Visibility
            Get
                Return _msVisiable
            End Get
            Set(value As Visibility)
                _msVisiable = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property GroupModel As GroupModel
            Get
                Return _groupModel
            End Get
            Set(value As GroupModel)
                _groupModel = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property ApplyCmd As RelayCommand
            Get
                Return _applyCmd
            End Get
            Set(value As RelayCommand)
                _applyCmd = value
            End Set
        End Property

        Public Property CancelCmd As RelayCommand
            Get
                Return _cancelCmd
            End Get
            Set(value As RelayCommand)
                _cancelCmd = value
            End Set
        End Property

        Public Property NotMsVisiable As Visibility
            Get
                Return _notMsVisiable
            End Get
            Set(value As Visibility)
                _notMsVisiable = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property IdList As ObservableCollection(Of String)
            Get
                Return _idList
            End Get
            Set
                _idList = Value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property AddCommand As RelayCommand
            Get
                Return _addCommand
            End Get
            Set(value As RelayCommand)
                _addCommand = value
            End Set
        End Property

        Public Property EditCommand As RelayCommand
            Get
                Return _editCommand
            End Get
            Set(value As RelayCommand)
                _editCommand = value
            End Set
        End Property

        Public Property IsAdd As Boolean
            Get
                Return _isAdd
            End Get
            Set(value As Boolean)
                _isAdd = value
                RaisePropertyChanged("IsAdd")
                RaisePropertyChanged("IsUpdate")
            End Set
        End Property

        Public Property IsUpdate As Boolean
            Get
                Return Not _isAdd
            End Get
            Set(value As Boolean)
                IsAdd = Not value
            End Set
        End Property

        Public Property StrReason As String
            Get
                Return _strReason
            End Get
            Set(value As String)
                _strReason = value
            End Set
        End Property

        Public Property ExhdEnable As Boolean
            Get
                Return _exhdEnable
            End Get
            Set(value As Boolean)
                _exhdEnable = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property Version113Visable As GridLength
            Get
                Return _version113Visable
            End Get
            Set(value As GridLength)
                _version113Visable = value
            End Set
        End Property

        Public Property LeakUnit As String
            Get
                Return _leakUnit
            End Get
            Set(value As String)
                _leakUnit = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property PressureUnit As String
            Get
                Return _pressureUnit
            End Get
            Set(value As String)
                _pressureUnit = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property Id As String
            Get
                Return _id
            End Get
            Set(value As String)
                If _id <> value AndAlso IsUpdate AndAlso (Not _isSwitchGroup) Then
                    FillEditModel(value)
                End If
                _id = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property GroupId As UShort
            Get
                Return _groupId
            End Get
            Set(value As UShort)
                _groupId = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property SwitchGroupCmd As RelayCommand
            Get
                Return _switchGroupCmd
            End Get
            Set(value As RelayCommand)
                _switchGroupCmd = value
            End Set
        End Property

        Public Property GroupIdList As ObservableCollection(Of String)
            Get
                Return _groupIdList
            End Get
            Set(value As ObservableCollection(Of String))
                _groupIdList = value
            End Set
        End Property

        Public Property IsNot113 As Visibility
            Get
                Return _isNot113
            End Get
            Set(value As Visibility)
                _isNot113 = value
            End Set
        End Property
    End Class

End Namespace
